﻿using System;
using JulMar.Windows.Mvvm;
using System.Collections.ObjectModel;
using MapInfo.Wrapper.Core.Extensions;
using MapInfo.Wrapper.MapOperations;
using NathansMapInfoProjects.WindowManager.Models;

namespace NathansMapInfoProjects.WindowManager.ViewModels
{
    public class ClosedWindowsViewModel : ViewModel
    {
        public ClosedWindowsViewModel()
        {
            this.ClosedWindows = new ObservableCollection<ClosedWindowViewModel>();
            this.IsUpdatesFrozen = true;
        }

        void Entry_WindowClosed(Window obj)
        {
            if (obj.Type == WindowTypes.Cart_Legend)
            {
                string isopen = Entry.Session.Eval("WindowInfo(WindowInfo({0},10),11)".FormatWith(obj.ID));
                if (isopen == null)
                    return;
            }
            
            ClosedWindow window = new ClosedWindow
                                      {
                                          CloseTime = DateTime.Now,
                                          WindowName = obj.Name,
                                          RestoreString = obj.CloneWindowCommand
                                      };

            // Insert a index 0 so that the last closed window is at the top.
            this.ClosedWindows.Insert(0, new ClosedWindowViewModel(window));
        }

        public ObservableCollection<ClosedWindowViewModel> ClosedWindows { get; set; }

        private bool isupdatesfrozen;

        public bool IsUpdatesFrozen
        {
            get
            {
                return this.isupdatesfrozen;
            }
            set
            {
                this.isupdatesfrozen = value;

                // If the updates are not frozen we need to add the handler to
                // to the closed window handler from MapInfo, else remove the handler so no
                // updates are processed.
                if (!value)
                    Entry.WindowClosed += this.Entry_WindowClosed;
                else
                    Entry.WindowClosed -= this.Entry_WindowClosed;

                base.OnPropertyChanged("IsUpdatesFrozen");
            }
        }
    }
}
